<?php
    @session_start();
    require_once 'shared-functions.php';
    require_once 'session.php';
    require_once 'masterpage.php';

    if(!IsValidSession())
    {
        header('Location: login.php?page=apply-fee');
        exit();
    }
    else
    {
        RefreshSession();
    }
	
	$user = GetCurrentUserAccessLevel();
	
	 //Check user access
    if($user == $STUDENT || $user == $TEACHER)
    {
        header('Location: login.php?page=apply-fee&error=Insufficient privilege level for applying fees to a student account&logout=1');
        exit();
    }

    if(!isset($_POST['StudentID']))
    {
        header('Location: student-selector.php?page=apply-fee');
        exit();
    }


    $link = connect_db();
    
    masterpage("Apply Fee");
	//Used for error checking
	$a = "";
	
	$_SESSION['dateTime'] = $dateTime = date('Y-m-d H:i:s');
	$_SESSION['studentID'] = $studentID = $_POST['StudentID'];
	//Apply Fee
	if(isset($_POST['type']) && isset($_POST['amount']) && isset($_POST['comment']))
	{
		$showMessage= false;
		$msg = "";
		$premsg = "<td class='altrows'>";
		
		$query = "SELECT * FROM `FeeLedger` WHERE `StudentID` = '".$_POST['StudentID']."';";
		$result = mysql_query($query, $link);
		
		$total = 0;
		while($ledgerEntry=mysql_fetch_array($result,MYSQL_BOTH))
		{
            $total +=$ledgerEntry['Amount'];
		}
		
		
		if($_POST['amount'] != "")
		{
			if(is_numeric($_POST['amount'] ))
			{
				//Validated... now perform adding the payment
				
				$amount = $_POST['amount'];
				
				if(!isset($_POST['revert']))
				{
					if($amount < 0)
					{
						$amount = -($amount);
					}
				}
				else //If reverting
				{
					if($amount > 0)
					{
						$amount = -($amount);
					}
					$_POST['comment'] = "Reverted last transaction";
				}
				
				$query = "INSERT INTO `FeeLedger` (`StudentID`,
								  `Date`,
								  `Type`,
								  `Amount`,
								  `Comment`,
								  `ProcessingUser`) VALUES
								  ('".$_POST['StudentID']."',
								   '".$dateTime."',
								   '".$_POST['type']."',
								   '".$amount."',
								   '".$_POST['comment']."',
								   '".GetSessionUser()."');";
				$result = mysql_query($query,$link);
				if(!$result)
				{
					$showMessage = true;
					$msg = "Oops something went wrong. Please contact support.";
					
					addLogEntry('FeeLedger', 'Unsuccessfully added '.$amount.' GHC fee for Student: '.$_POST['StudentID']);
				}
				else
				{	
					$showMessage = true;
					if(!isset($_POST['revert']))
					{
						$msg = "Fee of ".($amount)." GH&cent; added. [ <a href='print-receipt.php?type=fee' target='_blank'>Print Receipt</a> ]<form action='apply-fee.php' method='post'>
																		<input type='hidden' name='StudentID' value='".$_POST['StudentID']."' />
																		<input type='hidden' name='type' value='".$_POST['type']."' />
																		<input type='hidden' name='amount' value='".$_POST['amount']."' />
																		<input type='hidden' name='comment' value='".$_POST['comment']."' />
																		<input type='hidden' name='revert' value='1' />
																		<input type='submit' value='Revert' alt='Click here to revert the last payment' />
																	</form>";
						addLogEntry('FeeLedger', 'Added '.$amount.' GHC fee to Student: '.$_POST['StudentID']);
					}
					else
					{
						$msg = "Transaction reverted [ <a href='print-receipt.php' target='_blank'>Print Receipt</a> ]";
						addLogEntry('FeeLedger', 'Reverted '.$amount.' GHC fee to Student: '.$_POST['StudentID']);
					}
				}
			}
			else
			{
				$showMessage = true;
				$a = "<font color='red'>*</font>";
				$msg = $_POST['amount']." GH&cent; is not a valid amount. Please enter a corrent amount.";
			}
		} 
		else
		{
			$showMessage = true;
			$a = "<font color='red'>*</font>";
			$msg = "Please enter an amount";
		}
		
		if($showMessage)
		{
			echo '<table width="800"><tr class="altrows">'.$premsg.$msg.'</td></tr></table>';
		}
	}
?>
	<a href='student-selector.php?page=apply-fee'>&lt;&lt; Back to Student Selector</a>
	<br />
	<br />
    <table>
        <form action="apply-fee.php" method="post">
		<input type="hidden" name="StudentID" value="<?php echo $studentID; ?>"/>
        <tr><th class="tableTitle" colspan="2">Apply Fee</th></tr>
        <tr>
            <td class="fieldLabel">Student ID</td><td><?php echo $studentID; ?></td></tr>
        </tr>
<?php
		// Get Student Info to display
		$query = "SELECT FirstName, MiddleName, LastName, DOB
					FROM Student JOIN User
						ON Student.ID = User.UserId
					WHERE Student.ID = '$studentID';";
					
		$result = mysql_query($query,$link);
		$studentInfo = mysql_fetch_array($result,MYSQL_BOTH);
		
		echo "<tr><td class='fieldLabel'>Name</td>";
		echo "<td>".$studentInfo['FirstName']." ".$studentInfo['MiddleName']." ".$studentInfo['LastName']."</td></tr>";
		echo "<tr><td class='fieldLabel'>Birthday</td>";
		echo "<td>".date('d-m-Y', strtotime($studentInfo['DOB']))."</td></tr>";
?>
        <tr><td class="fieldLabel">Payment Category</td><td><select name="type">
<?php
		// Only allow librarian to apply Library Assessment Fees
		if (GetCurrentUserAccessLevel() == $LIBRARIAN)
		{
			$query = "SELECT * FROM `feeTypes` WHERE `description` LIKE '%Library%Assessment';";
			$result = mysql_query($query,$link);
			while($currentType=mysql_fetch_array($result,MYSQL_BOTH))
			{
				echo '<option value="'.$currentType['type'].'">'.$currentType['description']."</option>";
			}
		}
		else
		{
			$query = "SELECT * FROM `feeTypes` WHERE `description` LIKE '%Assessment';";
			$result = mysql_query($query,$link);
			while($currentType=mysql_fetch_array($result,MYSQL_BOTH))
			{
				echo '<option value="'.$currentType['type'].'">'.$currentType['description']."</option>";
			}
		}
?>
        </select></td></tr>
        <tr><td class="fieldLabel">Amount</td><td><input type="text" name="amount" /><?php echo $a;?></td></tr>
        <tr><td class="fieldLabel">Comment</td><td><textarea rows="5" cols="30" name="comment"></textarea></td></tr>
        <tr><td colspan="2" align="right"><input type="submit" value="Add Fee"/></td></tr>
        </form>
    </table>
    <br />
	
	<form action="student-billing-history.php" method="POST" target="_blank">
		<input type="submit" value="View Printer Friendly History"/>
		<input type="hidden" name="StudentID" value="<?php echo $studentID;?>"/>
	</form>
	
    <table class="DataList">
        <tr><th class="header" colspan="5">Payment History</th></tr>
        <tr>
            <th class="header">Date</th>
            <th class="header">Transaction Type</th>
            <th class="header">Amount</th>
            <th class="header">User</th>
            <th class="header">Notes</th>
        </tr>
<?php
        $query = "SELECT `FeeLedger`.`Date`, 
                         `FeeLedger`.`Amount`,
                         `FeeLedger`.`ProcessingUser`,
                         `FeeLedger`.`Comment`,
                         `feeTypes`.`description`
                         FROM `FeeLedger`,`feeTypes` WHERE `StudentID`='".$_POST['StudentID']."' AND `FeeLedger`.`Type`=`feeTypes`.`type` ORDER BY `Date` ASC;";
        $result = mysql_query($query,$link);
        $accountBalance = 0;
		$rowID = 0;
        while($ledgerEntry=mysql_fetch_array($result,MYSQL_BOTH))
        {
		
			if ($rowID == 0)
			{
				$rowClass = "rows";
				$rowID++;
			}
			else
			{
				$rowClass = "altrows";
				$rowID--;
			}
			
            $accountBalance+=$ledgerEntry['Amount'];
            echo '<tr class="'.$rowClass.'">';
            echo '<td>'. date('d-m-Y H:i:s', strtotime($ledgerEntry['Date'])) ."</td>";
            echo '<td>'.$ledgerEntry['description']."</td>";
            echo '<td>'.$ledgerEntry['Amount']."</td>";
            echo '<td>'.$ledgerEntry['ProcessingUser']."</td>";
            echo '<td>'.$ledgerEntry['Comment']."</td>";
            echo '</tr>';
        }
        echo '<tr><td></td><td>Current Balance</td><td>'.number_format($accountBalance,2).' GH&cent;</td><td></td><td></td></tr>';
?>
    </table>

<?php
	echo "<br/>";
	echo "<form action='process-payment.php' method='POST'>";
	echo "<input type='submit' value='Go to Process Payment Page'/>";
	echo "<input type='hidden' name='StudentID' value='$studentID'/>";
	echo "</form>";

	endmasterpage();
?>

